package org.jeecg.config;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import io.swagger.annotations.ApiResponse;
import jdk.nashorn.internal.ir.RuntimeNode;
import org.jeecg.modules.shiro.vo.DefContants;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;

import io.swagger.annotations.ApiOperation;
import springfox.documentation.builders.*;
import springfox.documentation.service.*;
import lombok.extern.slf4j.Slf4j;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @Author scott
 */
@Slf4j
@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUI
public class Swagger2Config implements WebMvcConfigurer {

    /**
     * 显示swagger-ui.html文档展示页，还必须注入swagger资源：
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    /**
     * swagger2的配置文件，这里可以配置swagger2的一些基本的内容，比如扫描的包等等
     *
     * @return Docket
     */
    @Bean
    public Docket createRestApi() {
        List<ResponseMessage> responseMessageList = new ArrayList<>();
        responseMessageList.add(new ResponseMessageBuilder().code(100).message("ARGS_ERROR").build());
        responseMessageList.add(new ResponseMessageBuilder().code(101).message("SIGN_ERROR").build());
        responseMessageList.add(new ResponseMessageBuilder().code(102).message("ILLEGAL_EQUIPMENT_ERROR").build());
        responseMessageList.add(new ResponseMessageBuilder().code(120).message("ILLEGAL_PAYORDER_ERROR").build());
        responseMessageList.add(new ResponseMessageBuilder().code(200).message("SUCCESS").build());
        responseMessageList.add(new ResponseMessageBuilder().code(300).message("FAIL").build());
        responseMessageList.add(new ResponseMessageBuilder().code(500).message("SERVER ERROR").build());
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .globalResponseMessage(RequestMethod.GET, responseMessageList)
                .globalResponseMessage(RequestMethod.POST, responseMessageList)
                .globalResponseMessage(RequestMethod.DELETE, responseMessageList)
                .globalResponseMessage(RequestMethod.PUT, responseMessageList)
                .select()
                //此包路径下的类，才生成接口文档
                .apis(RequestHandlerSelectors.basePackage("org.jeecg.modules.api"))
                //加了ApiOperation注解的类，才生成接口文档
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(Collections.singletonList(securityScheme()));
        //.globalOperationParameters(setHeaderToken());
    }

    /***
     * oauth2配置
     * 需要增加swagger授权回调地址
     * http://localhost:8888/webjars/springfox-swagger-ui/o2c.html
     * @return
     */
    @Bean
    SecurityScheme securityScheme() {
        return new ApiKey(DefContants.X_ACCESS_TOKEN, DefContants.X_ACCESS_TOKEN, "header");
    }

    /**
     * JWT token
     *
     * @return
     */
    private List<Parameter> setHeaderToken() {
        ParameterBuilder tokenPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<>();
        tokenPar.name(DefContants.X_ACCESS_TOKEN).description("token").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
        pars.add(tokenPar.build());
        return pars;
    }

    /**
     * api文档的详细信息函数,注意这里的注解引用的是哪个
     *
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                // //大标题
                .title("posp服务API接口文档")
                // 版本号
                .version("1.0")
//				.termsOfServiceUrl("NO terms of service")
                // 描述
                .description("后台API接口</br>全局使用UTF-8编码</br>SignatureKey由服务端提供，最大长度64（服务端自定），为一组字符串，作为双方签名认证使用。\n" +
                        "1、对所有传入参数按照字段名的ASCII码从小到大排序(字典序)后，使用URL键值对应格式（即“key1=value1&key2=value2...”）拼接成字符 string1, 注意：为空的参数不参与签名。\n" +
                        "2、在第1步中的string1最后拼接上“&SignatureKey=Key”（密钥）得到string2字符串（即“key1=value1&key2=value2&key=abcdefghijklmn”），然后对string2进行md5运算，再将得到的字符串所有字符转换为大写得到signature字段。\n")
                // 作者
                .contact("Dean")
                .build();
    }

}
